package com.coollang.smartbra.base;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;

import com.coollang.smartbra.R;
import com.coollang.smartbra.activity.LoginActivity;
import com.coollang.smartbra.bleutil.BleUtil;
import com.coollang.smartbra.model.LogInDataBean;
import com.coollang.smartbra.utils.DataUtils;
import com.coollang.smartbra.utils.NetUtils;
import com.coollang.smartbra.utils.PreferencesUtils;
import com.coollang.smartbra.utils.TimeUtils;
import com.coollang.smartbra.utils.ToastUtils;
import com.coollang.smartbra.utils.UIUtils;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.umeng.socialize.Config;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.common.QueuedWork;
import com.zhy.autolayout.config.AutoLayoutConifg;

import org.litepal.LitePalApplication;

import cn.pedant.sweetalert.SweetAlertDialog;
import io.realm.Realm;
import io.realm.RealmConfiguration;

/**
 * @author Timmy
 *         说明：a
 *         <p/>
 *         时间：2016-2-19 下午2:02:11
 */
public class MyApplication extends LitePalApplication {
    private static final String TAG = "MyApplication";
    private static MyApplication mContext; //全局上下文
    //跑步设置  声音播报 自动暂停 屏幕常亮 自动锁屏
    public static boolean isSound = false;
    public static boolean isStop = false;
    public static boolean isLight = false;
    public static boolean isLock = false;
    public static LogInDataBean mLogInDataBean;
    public Bitmap selectBitmap;
    //用户个人信息
    public static String userName;//昵称
    public static String register_day;//注册时间
    //用户运动数据
    //是否连接设备
    public boolean isConnected = false;
    // 蓝牙设备PID
    private Handler mMainThreadHandler;

    public SweetAlertDialog pDialog;
    public int betery;//硬件电量
    public String version = "0.1";//版本号
    public String deviceName;//连接的设备名称
    public String deviceMac;//连接的设备名称
    public boolean isUpdating = false;//正在升级

    private int mFinalCount = 0;
    public static boolean isActive; //全局变量

    //在自己的Application中添加如下代码
    private ProgressDialog mProgressDialog;

    @Override
    public void onCreate() {
        super.onCreate();
        this.mContext = this;

        initOkGo();
        initRealm();

        // 友盟分享
        initUMShare();

        //初始化fresco
        Fresco.initialize(this);
        initHandler();
        PreferencesUtils.putBoolean(this, "hasNewVersion", false);
        registerActivityLifecycle();

        AutoLayoutConifg.getInstance().useDeviceSize();

        BleUtil.init(this);
    }


    private void initOkGo() {                  //全局公共参数
        OkGo.init(this);
        OkGo.getInstance()
                 //.debug("gzw", Level.OFF, true)
                .setCacheMode(CacheMode.FIRST_CACHE_THEN_REQUEST)
                .setCacheTime(5 * 60000);
    }

    private void initRealm() {
        Realm.init(this);

        try {
            RealmConfiguration config = new RealmConfiguration.Builder()
                    .name("mf.realm")
                    .schemaVersion(33)
                    .deleteRealmIfMigrationNeeded()
                    .build();

            Realm.setDefaultConfiguration(config);

        } catch (RuntimeException e) {
            Realm.deleteRealm(Realm.getDefaultConfiguration());
            Realm.getInstance(new RealmConfiguration.Builder()
                    .deleteRealmIfMigrationNeeded()
                    .name("mf.realm")
                    .schemaVersion(32)
                    .build());
        }
    }

    private void initUMShare() {
        Config.DEBUG = false;
        QueuedWork.isUseThreadPool = false;
        UMShareAPI.get(this);
        com.umeng.socialize.utils.Log.LOG = false;
    }

    {
        PlatformConfig.setWeixin("wxbd18ce096c5fe1e4", "3595d0b4d902d82295088a7f56f61e9b");
        PlatformConfig.setQQZone("1106277035", "KEYV9TspJa6XEiQdfth");
        PlatformConfig.setSinaWeibo("4202123291", "82981a0253583654458b8ada660e72cd", "http://sns.whalecloud.com");
    }


    private void registerActivityLifecycle() {
        //判断应用处于前台还是后台
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

            }

            @Override
            public void onActivityStarted(Activity activity) {
                mFinalCount++;
                //如果mFinalCount ==1，说明是从后台到前台
                if (mFinalCount == 1) {
                    //说明从后台回到了前台
                    isActive = true;
                    muteAudioFocus(mContext, true);
                }
            }

            @Override
            public void onActivityResumed(Activity activity) {
            }

            @Override
            public void onActivityPaused(Activity activity) {
            }

            @Override
            public void onActivityStopped(Activity activity) {
                mFinalCount--;
                // 如果mFinalCount == 0，说明是前台到后台
                if (mFinalCount == 0) {
                    //说明从前台回到了后台
                    isActive = false;
                }
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {

            }
        });
    }

    // 屏蔽音乐
    @TargetApi(Build.VERSION_CODES.FROYO)
    public static boolean muteAudioFocus(Context context, boolean bMute) {
        if (context == null) {
            Log.d("ANDROID_LAB", "context is null.");
            return false;
        }

        boolean bool = false;
        AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        if (bMute) {
            int result = am.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
            bool = result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
        } else {
            int result = am.abandonAudioFocus(null);
            bool = result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
        }
        return bool;
    }


    /**
     * 判断是否是中文
     * 不考虑通过locale.getCountry()来进行语言环境判断，是因为有用户的语言选项中出现（香港地区，英文）的选项。
     * 语言环境是英文，但是地区是HK
     */
    public boolean isChinese() {
        return getResources().getConfiguration().locale.getLanguage().equalsIgnoreCase("zh");
    }

    public static MyApplication getApplication() {
        return mContext;
    }

    private void initHandler() {
        this.mMainThreadHandler = new Handler();
    }

    /**
     * 对外暴露一个主线程的handelr
     */
    public Handler getMainThreadHandler() {
        return mMainThreadHandler;
    }

    /**
     * 校准时间戳
     */
    public void sendDate() {
        long time = TimeUtils.getCurrentTimeUnixLong() - TimeUtils.changeStrDateToLongDate("1970-01-01 00:00:00");

        byte[] timetobyte = DataUtils.longtobyte(time);
        Integer iO = new Integer(Integer.parseInt(MyApplication.mLogInDataBean.getHr_alarm()));

        byte b = iO.byteValue();

        String isalarm = mLogInDataBean.getIsalarm();
        int i = Integer.parseInt(isalarm);
        if (i == 1) {
            BleUtil.getInstance().sendData((byte) 0x11, timetobyte[0], timetobyte[1], timetobyte[2], timetobyte[3], (byte) 0x01, b);
        } else {
            BleUtil.getInstance().sendData((byte) 0x11, timetobyte[0], timetobyte[1], timetobyte[2], timetobyte[3], (byte) 0x00, b);
        }
    }

    /**
     * 加载公共弹窗
     *
     * @param activity
     */
    public void showDialog(Activity activity) {
        pDialog = new SweetAlertDialog(activity, SweetAlertDialog.PROGRESS_TYPE).setTitleText("Loading");
        pDialog.setCancelable(true);
        pDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {

            }
        });
        pDialog.show();
    }

    public void showProgressDialog(String title, String message, Context context) {
        if (mProgressDialog == null) {
            mProgressDialog = ProgressDialog.show(context, title, message, false);
        } else if (mProgressDialog.isShowing()) {
            mProgressDialog.setTitle(title);
            mProgressDialog.setMessage(message);
        }
        mProgressDialog.show();
    }

    public void dismiss() {
        if (pDialog != null && pDialog.isShowing()) {
            pDialog.dismiss();
            pDialog = null;
        }
    }

    public void dialogdissmiss() {
        if (pDialog != null && pDialog.isShowing()) {
            pDialog.setTitleText("Success!")
                    .setConfirmText("OK")
                    .changeAlertType(SweetAlertDialog.SUCCESS_TYPE);
            MyApplication.getApplication().getMainThreadHandler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    pDialog.dismiss();
                    pDialog = null;
                }
            }, 1000);
        }
    }

    public void hideProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }

    /**
     * 断开连接
     */
    public void disConnectDevice() {
        if (isConnected) {
            BleUtil.getInstance().disconnect();
            isConnected = false;
        }
    }

    public void needLoginAgain() {
        Realm defaultInstance = Realm.getDefaultInstance();

        defaultInstance.beginTransaction();
        defaultInstance.deleteAll();
        defaultInstance.commitTransaction();

        disConnectDevice();
        ActivityCollector.finishAll();
        restartApp();
    }

    /**
     * 重启应用
     */
    public static void restartApp() {
        Intent intent = new Intent(MyApplication.getApplication(), LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        MyApplication.getApplication().startActivity(intent);
        android.os.Process.killProcess(android.os.Process.myPid()); // 结束进程之前可以把你程序的注销或者退出代码放在这段代码之前
    }

    /**
     * 是否有网络提醒
     */
    public boolean hasNet() {
        if (NetUtils.hasNet(getApplicationContext())) {
            return true;
        } else {
            ToastUtils.showToast(UIUtils.getString(R.string.no_net));
            return false;
        }
    }

    /**
     * 是否有连接设备
     *
     * @return
     */
    public boolean hasConnected() {
        if (isConnected) {
            return true;
        } else {
            ToastUtils.showToast(UIUtils.getString(R.string.ble_disconnect));
            return false;
        }
    }
}
